﻿// MIT License

// Copyright (c) 2021-2023 1024


namespace Kyx.Application;

public class SysLogService : ISysLogService, ITransient
{
    private readonly IRepository<SysLogVis> _logVisRep;

    public SysLogService(IRepository<SysLogVis> logVisRep)
    {
        _logVisRep = logVisRep;
    }

    public async Task<long> AddVisLogAsync(SysUser user, LoginType visType)
    {
        var client = AppEx.GetWebInfo();

        var log = new SysLogVis
        {
            Name = user.Realname,
            Success = true,
            Message = "",
            Ip = App.HttpContext.GetIpV4(),
            Browser = client.Browser,
            Os = client.Os,
            VisType = visType,
            VisTime = DateTimeOffset.Now,
            Account = user.Account,
            Location = App.HttpContext.Request.Path
        };

        switch (visType)
        {
            case LoginType.LOGIN:
                log.Message = "登录成功";
                break;
            case LoginType.LOGOUT:
                log.Message = "注销成功";
                break;
            case LoginType.REGISTER:
                log.Message = "注册成功";
                break;
            case LoginType.CHANGEPASSWORD:
                log.Message = "修改密码成功";
                break;
            case LoginType.AUTHORIZEDLOGIN:
                log.Message = "第三方授权登录成功";
                break;
        }

        await _logVisRep.InsertNowAsync(log);

        return log.Id;
    }
}
